package ar.com.ctrln.view.dashboard.administracion.cliente;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.VariableResolver;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zk.ui.select.annotation.WireVariable;
import org.zkoss.zul.Label;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.ListModelList;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Textbox;

import ar.com.ctrln.control.administracion.cliente.ConsultarClientes;
import ar.com.ctrln.persistence.model.cliente.Cliente;
import ar.com.ctrln.view.ui.comportamientoVentana.AbstractMinimizarVentana;

@VariableResolver(org.zkoss.zkplus.spring.DelegatingVariableResolver.class)
public class ConsultarClienteController extends AbstractMinimizarVentana {

	private static final long serialVersionUID = -5026484941900569851L;

	@WireVariable
	private ConsultarClientes consultarClientes;

	private List<Cliente> clientes;

	@Wire
	private Listbox lbClientes;

	@Wire("#txtFilter")
	private Textbox txtFilter;


	@Wire
	private Label footer_label;


	@Override
	public void doAfterCompose(Component comp) throws Exception {
		super.doAfterCompose(comp);
		clientes = consultarClientes.listaClientes();
		ListModelList<Cliente> modelo = new ListModelList<Cliente>();
		modelo.addAll(clientes);
		lbClientes.setModel(modelo);
	}

	public ListModel<Cliente> getConsultaCliente() {
		clientes = consultarClientes.listaClientes();
		return new ListModelList<Cliente>(clientes);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Listen("onChanging = #txtFilter")
	public void getFilter(Event event) {
		((Textbox) event.getTarget())
				.setValue(((org.zkoss.zk.ui.event.InputEvent) event).getValue());
		lbClientes.setModel(new ListModelList(getFilterBy(txtFilter.getValue(),
				clientes)));
		if (lbClientes.getItemCount() > 0) {
			footer_label.setValue("");
			footer_label.setValue("Un total de " + lbClientes.getItemCount()
					+ " Clientes");
		} else {
			footer_label.setValue("Ningun Resultado...");
			footer_label.setValue("");
		}
		((Textbox) event.getTarget()).setFocus(true);
	}

	public static List<Cliente> getFilterBy(String condicion,
			Collection<Cliente> clientes) {
		List<Cliente> data = new ArrayList<Cliente>();
		for (Iterator<Cliente> i = clientes.iterator(); i.hasNext();) {
			Cliente tmp = i.next();
			if (tmp.getRazonSocial().toLowerCase()
					.indexOf(condicion.trim().toLowerCase()) >= 0
					|| tmp.getTipoActividad().getNombreTipoActividad()
							.toLowerCase()
							.indexOf(condicion.trim().toLowerCase()) >= 0) {
				data.add(tmp);
			}
		}
		return data;
	}
}
